package com.hskn.hss.module.tloilcostcfg.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.file.FileUploadUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.costdictitem.service.ICostDictItemService;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.file.service.IFileService;
import com.hskn.hss.module.file.service.impl.FileServiceImpl;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.module.tloilcostcfg.entity.TlOilcostCfg;
import com.hskn.hss.module.tloilcostcfg.mapper.TlOilcostCfgMapper;
import com.hskn.hss.module.tloilcostcfg.service.ITlOilcostCfgService;
import com.hskn.hss.module.tloilcostcfg.to.TlOilcostCfgListTO;
import com.hskn.hss.module.tloilcostcfg.vo.TlOilcostCfgExecelTemplateVO;
import com.hskn.hss.module.tloilcostcfg.vo.TlOilcostCfgExecelVO;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-05
 */
@Slf4j
@RestController
@RequestMapping("/hss/tloilcostcfg")
@Api(tags = {"-tl_oilcost_cfg"}, description = "车辆油费")
public class TlOilcostCfgController {

    @Autowired
    private ITlOilcostCfgService tlOilcostCfgService;
    @Resource
    private TlOilcostCfgMapper oilcostCfgMapper;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ICostDictItemService costDictItemService;
    @Autowired
    private ITlCarService carService;
    @Autowired
    private ITlCarTypeService carTypeService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IFileService fileService;


    /***
     * 新增信息
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_oilcost_cfg", bean = TlOilcostCfg.class, beanMapper = TlOilcostCfgMapper.class, names = "carnumid", twoBeanMapper = TlCarMapper.class, twoNames = "carnumber")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        return tlOilcostCfgService.insert(params);
    }

    /**
     * 修改信息
     *
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_oilcost_cfg", idKey = "id", bean = TlOilcostCfg.class, beanMapper = TlOilcostCfgMapper.class, names = "carnumid", twoBeanMapper = TlCarMapper.class, twoNames = "carnumber")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult update(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        return tlOilcostCfgService.update(params);
    }

    /***
     * 删除角色信息
     * @param forIdsTO
     * @return
     */
    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_oilcost_cfg", idKey = "ids", bean = TlOilcostCfg.class, beanMapper = TlOilcostCfgMapper.class,
            names = "carnumid", twoTableName = "tl_car", twoBeanMapper = TlCarMapper.class, twoNames = "carnumber")
    @RequestMapping(value = "deleteByid", method = RequestMethod.POST)
    public AjaxResult deleteByid(@RequestBody @Validated ForIdsTO forIdsTO) {
        return tlOilcostCfgService.deleteByid(forIdsTO);
    }

    /**
     * 根据Id获取信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getitemByid", method = RequestMethod.POST)
    public AjaxResult getitemByid(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        TlOilcostCfg tlOilcostCfg = null;
        try {
            tlOilcostCfg = tlOilcostCfgService.getitemByid(params.getString("id"));
            return AjaxResult.success(tlOilcostCfg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
    }

    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public AjaxResult getList(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject json = tlOilcostCfgService.listOilCost(entity, params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }

    /**
     * 车辆油费导入接口
     *
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_oilcost_cfg", bean = TlOilcostCfg.class, beanMapper = TlOilcostCfgMapper.class, isImport = true)
    @ApiOperation(value = "车辆油费导入接口", notes = "车辆油费导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request, @ModelAttribute @Validated ExcelReaderTO excelReaderTo, @RequestParam("files") MultipartFile file) {
        try {
            if (Arrays.stream(ExcelTypeEnum.values()).noneMatch(s -> s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))) {
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlOilcostCfg> util = new ExcelUtil<TlOilcostCfg>(TlOilcostCfg.class);
            List<TlOilcostCfg> oilcostCfgList = util.importExcel(inputStream);
            if (oilcostCfgList.isEmpty()) {
                return AjaxResult.fail("导入内容为空");
            }
            tlOilcostCfgService.excelReader(oilcostCfgList);
            if (tlOilcostCfgService.saveBatch(oilcostCfgList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    @ApiOperation(value = "油费导出接口", notes = "油费导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlOilcostCfgExecelVO.class)
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request, @RequestBody TlOilcostCfgListTO oilcostCfgListTO) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if((oilcostCfgListTO.getIds()!=null&&oilcostCfgListTO.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            //查询数据
            List<TlOilcostCfg> oilcostCfgList = tlOilcostCfgService.getTlOilcostCfgList(oilcostCfgListTO, format);

//            Map<String, CostDictItem> costDictItemMap = costDictItemService.getCostDictItemMap(new QueryWrapper<>());
            //工具类实例化
            ExcelUtil<TlOilcostCfgExecelVO> util = new ExcelUtil<TlOilcostCfgExecelVO>(TlOilcostCfgExecelVO.class);
            //数据载体转换
            List<TlOilcostCfgExecelVO> tlOilcostCfgExecelVOList = new ArrayList<>();
            //构造结果集
            Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
            Map<String, TlCarType> carTypeMap = carTypeService.getCarTypeMap(new QueryWrapper<>());
            Map<String, TlCar> carMap = carService.getCarMap(new QueryWrapper<>());
            Map<String, User> userMap = userService.getUserMap();
            for (TlOilcostCfg tlOilcostCfg : oilcostCfgList) {
                TlCar car = carMap.containsKey(tlOilcostCfg.getCarnumid())?carMap.get(tlOilcostCfg.getCarnumid())
                        :new TlCar();
                TlCarType carType = carTypeMap.containsKey(car.getCartypeid())?carTypeMap.get(car.getCartypeid())
                        :new TlCarType();
                User user = userMap.containsKey(car.getDriverid())?userMap.get(car.getDriverid())
                        :new User();
                SysDepart depart = departMap.containsKey(tlOilcostCfg.getDeptid())?departMap.get(tlOilcostCfg.getDeptid())
                        :new SysDepart();
                tlOilcostCfgExecelVOList.add(TlOilcostCfgExecelVO.buildTlOilcostCfgExecelVO(tlOilcostCfg,car,carType,user,depart));
            }
            //            导出
            tlOilcostCfgExecelVOList = tlOilcostCfgExecelVOList.stream().sorted(Comparator.comparing(TlOilcostCfgExecelVO::getCosttime)).collect(Collectors.toList());
            return util.exportExcel(tlOilcostCfgExecelVOList, "车辆油量");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }

    @ApiOperation(value = "车辆油费导出模板接口", notes = "车辆油费模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlOilcostCfgExecelVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<TlOilcostCfgExecelTemplateVO> util = new ExcelUtil<TlOilcostCfgExecelTemplateVO>(TlOilcostCfgExecelTemplateVO.class);
            //数据载体转换
            List<TlOilcostCfgExecelTemplateVO> oilcostCfgExecelVoList = new ArrayList<>();
            //导出
            return util.exportExcel(oilcostCfgExecelVoList, "车辆油费模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

